# coding: utf-8

from django.db import models
from django.contrib.auth.models import AbstractUser
from me.db_utils import ShortUUIDField
from rest_framework.authtoken.models import Token
from jsonfield import JSONField
from me.db_utils import uuid1_hex


class User(AbstractUser):
    id = ShortUUIDField('用户标识', primary_key=True, max_length=10)

    avatar = models.CharField("头像", max_length=300, blank=True, null=True)
    nickname = models.CharField("昵称", max_length=16, default='', blank=True)
    gender = models.IntegerField("性别", choices=((0, '女',), (1, '男'),), default=0)
    phone = models.CharField("电话", max_length=16, default='', blank=True)


class WXAppToken(Token):
    """
    小程序微信登录Token
    """
    class Meta:
        verbose_name = "WXAppToken"
        verbose_name_plural = "WXAppTokens"

    @classmethod
    def update_token(cls, user):
        token, res = WXAppToken.objects.update_or_create(user=user)
        return token.key

    @classmethod
    def get_token(cls, user):
        token = WXAppToken.objects.filter(user=user).first()
        if token:
            return token.key
        else:
            return WXAppToken.update_token(user)


class UserAuth(models.Model):
    user = models.ForeignKey(User, on_delete=True, verbose_name="用户")
    open_id = models.CharField("第三方登录标识", max_length=200)
    types = (
        ('weixin', 'weixin', ),
    )
    third_party_type = models.CharField("第三方登录类型", choices=types, max_length=10)
    extras = JSONField(u'附加信息', default={})

    class Meta:
        verbose_name = u'用户第三方登录信息'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.user

    @classmethod
    def get_or_create(cls, openid, third_type):
        user_auth = UserAuth.objects.filter(open_id=openid, third_party_type=third_type).first()
        if user_auth is None:
            user = User.objects.create(username=uuid1_hex())
            user_auth = UserAuth.objects.create(user=user, open_id=openid, third_party_type=third_type)
        return user_auth